#!/bin/bash

# shellcheck disable=SC1091
. ../../lib/shflags

DEFINE_string "username" 'admin' 'username' 'u'
DEFINE_string "password" "$(cat /proc/sys/kernel/random/uuid)" 'password' 'p'
DEFINE_string "logdir" '' 'log directory' 'l'

FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"

mkdir -p ~/nginx/conf.d && mkdir -p ~/log/nginx && mkdir -p ~/nginx/html

echo "${FLAGS_username}:$(openssl passwd -apr1 "${FLAGS_password}")" >.htpasswd

echo "username: ${FLAGS_username} password: ${FLAGS_password}"

cp ./default.conf ~/nginx/conf.d
cp ./logviewer.conf ~/nginx/conf.d
cp ./.htpasswd ~/nginx/conf.d

docker stop nginx-gw >>/dev/null 2>&1
docker rm nginx-gw >>/dev/null 2>&1

docker run --name nginx-gw --restart=always \
    -v ~/nginx/conf.d:/etc/nginx/conf.d \
    -v ~/log/nginx:/var/log/nginx \
    -v ~/nginx/html:/usr/share/nginx/html \
    -v "${FLAGS_logdir}":/var/log/outside \
    -d -p 7000:7000 -p 80:80 nginx \
    sh -c "mkdir -p /var/log/outside && nginx -g 'daemon off;'"
